﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Filter;
using Newtonsoft.Json.Linq;
using HttpUtility;
using WechatModel;

namespace WechatDAL
{
    public class W_OAuthDal
    {
        /// <summary>
        /// 获取授权网页地址（公众号和企业号可以通用）
        /// </summary>
        /// <param name="wt">服务号类型：0=公众号，1=企业号</param>
        /// <param name="url">回调地址，授权后跳转到的页面</param>
        /// <param name="type">授权类型：snsapi_base静默授权，用户几乎无感知，但只能获取openid; snsapi_userinfo需用户同意，可获取用户基本信息</param>
        /// <param name="state">自定义参数</param>
        /// <returns></returns>
        public static string GetOAuthAddress(int wt, string url, string type, string state)
        {
            url = System.Web.HttpContext.Current.Server.UrlEncode(url);
            return string.Format(wt == 0 ? WechatAPI4Public.OAuth : WechatAPI4Ent.OAuth, url, type, string.IsNullOrEmpty(state) ? "" : ("&state=" + state));
        }

        /// <summary>
        /// 获取网页授权结果
        /// </summary>
        /// <returns></returns>
        public W_OAuthInfo GetOAuthToken(string code)
        {
            JObject jo = Poster.Get(string.Format(WechatAPI4Public.OAuthToken, code));
            if (jo == null)
                return null;
            else
            {
                if (jo["errcode"] != null)  //错误40029
                {
                    return null;
                }
                else
                {
                    W_OAuthInfo m = new W_OAuthInfo();
                    m.access_token = jo["access_token"].ToString();
                    m.expires_in = Convert.ToInt32(jo["expires_in"].ToString());
                    m.refresh_token = jo["refresh_token"].ToString();
                    m.openid = jo["openid"].ToString();
                    m.scope = jo["scope"].ToString();
                    return m;
                }
            }
        }

        /// <summary>
        /// 企业号获取网页授权用户信息
        /// </summary>
        /// <param name="code"></param>
        /// <param name="aid"></param>
        /// <returns></returns>
        public string GetOAuthUserinfoEnt(string code, int aid)
        {
            JObject jo = Poster.Get(string.Format(WechatAPI4Ent.OAuthUserinfo, code, aid));
            if (jo == null)
                return "";
            else
            {
                if (jo["UserId"] != null)
                {
                    return jo["UserId"].ToString();
                }
                else
                {
                    return "";
                }
            }
        }
    }
}
